package cn.edu.hznu.notebook.controller;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.hznu.notebook.entity.ResponseResult;
import cn.edu.hznu.notebook.entity.User;
import cn.edu.hznu.notebook.service.UserService;

@Controller
public class PageController {
	
	Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	UserService userService;
	
	@RequestMapping(value = "/")
	public String getIndex(HttpSession session) {
		if(session.getAttribute("user") ==  null) {
			return "index";
		} else {
			return "home";
		}
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String getLogin() {
		return "index";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public ResponseResult login(
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password,
			HttpSession session) {
		ResponseResult result = new ResponseResult();
		result.setSucceeded(true);
		User user = this.userService.signIn(username);
		if (user == null) {
			result.setSucceeded(false);
			result.setMessage("User name is error.");
		} else if (!user.getPassword().equals(password)) {
			result.setSucceeded(false);
			result.setMessage("Password is error.");
		}
		session.setAttribute("user", user);
		return result;
	}
	
	@RequestMapping(value = "/home")
	public String getHome() {
		return "home";
	}

}
